# -*- encoding: utf-8 -*-
############################################################################
#    Copyright (C) 2007-2010 by Håvard Gulldah                             #
#    havard@gulldahl.no                                                    #
#                                                                          #
#    This program is free software; you can redistribute it and#or modify  #
#    it under the terms of the GNU General Public License as published by  #
#    the Free Software Foundation; either version 2 of the License, or     #
#    (at your option) any later version.                                   #
#                                                                          #
#    This program is distributed in the hope that it will be useful,       #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of        #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         #
#    GNU General Public License for more details.                          #
#                                                                          #
#    You should have received a copy of the GNU General Public License     #
#    along with this program; if not, write to the                         #
#    Free Software Foundation, Inc.,                                       #
#    59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             #
############################################################################

import logging

# Create your views here.
from django.contrib.auth import authenticate as django_auth, login as django_login
from django.core import serializers
from django.http import HttpResponse, HttpResponseRedirect, \
    HttpResponseBadRequest, HttpResponseNotAllowed, HttpResponseNotFound
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.auth.decorators import login_required
from ejejeweb.ejeje.models import *

def index(request):
    return render_to_response('ejeje/index.html', {'req':request})

def dashboard(request, json=False):
    from django.db import connection
    print connection.queries
    return render_to_response('ejeje/index.html', {})

def search(request, format=None):
    if format is None or format not in ('html', 'atom', 'json'):
        format = 'html'
    from searchviews import Search
    #initial querySet
    querySet = Journalpost.objects.all()
    s = Search(request, querySet)
    if format == "json":
        return s.getDatatablesJSON()
    elif format == "atom":
        return s.getFeed()
    else:
        return s.getHtml()
        
from django.contrib.auth.decorators import login_required

def history(request, json=False):
    ctx = {'object':None, 'req':request, 'view':'historikk'}
    try: 
        ctx['list'] = request.user.sok_set.all()
    except AttributeError:
        return render_to_response('ejeje/require-login.html', ctx)
    return render_to_response('ejeje/history.html', ctx)

def agent(request, json=False):
    ctx = {'object':None, 'req':request, 'view':'agent', 'newagent':None}
    if 'makeagent' in request.POST and request.POST['makeagent'] == '1':
        agent = None
        if request.user.is_authenticated():
            logging.debug("registering agent for %s", request.user)
            try:
                agent = request.user.agent_set.create(tekst=request.POST['searchstring'].encode('utf8'))
                logging.debug("agent added: %s", agent)
            except KeyError:
                logging.warning("unkonwon post request in agent")
                return HttpResponseBadRequest("Illegal HTTP POST data")
            else:
                if json:
                    return HttpResponse("""{"agent_added":true}""")
                else:
                    ctx['newagent'] = agent
    try: 
        ctx['list'] = request.user.agent_set.all()
    except AttributeError:
        return render_to_response('ejeje/require-login.html', ctx)
    return render_to_response('ejeje/agent.html', ctx)

def requestdoc(request, journalpost_id=None, request_id=None, json=False):
    ctx = {'object':None, 'req':request, 'list':[], 'template':'ejeje/layout.html'}
    template = 'ejeje/requestdoc.html'
    
    if journalpost_id is not None:
        ctx['object'] = get_object_or_404(Journalpost, pk=journalpost_id)
        template = "ejeje/requestdoc-new.html"
        if 'makerequest' in request.POST and request.POST['makerequest'] == '1':
            # POSTing a document request, i.e. confirming the request
            from utils import Documentrequest
            if 'email' in request.POST:
                ctx['docreq'] = Documentrequest(email=request.POST['email'].encode('utf8'),
                                                docid=journalpost_id)
            elif 'username' in request.POST and request.POST['username'].encode('utf8') == request.user.username and request.user.is_authenticated():
                ctx['docreq'] = Documentrequest(user=request.user,
                                                docid=journalpost_id)
            else:
                logging.debug("unkonwon post request")
                return HttpResponseBadRequest("Illegal HTTP POST data")
            ctx['docreq'].send()
            template ="ejeje/requestdoc-requested.html"
    elif request_id is not None:
        ctx['object'] = get_object_or_404(Innsyn, pk=request_id)
    else:
        if request.user.is_authenticated():
            ctx['list'] = request.user.innsyn_set.all()
    if 'frameless' in request.GET and request.GET['frameless'] == '1':
        ctx['template'] = 'ejeje/details.html'
    return render_to_response(template, ctx)

def requestagain(request, json=False):
    return render_to_response('ejeje/requestagain.html', {})

def directory(request, json=False):
    ctx = {'object':None, 'list':Postjournal.objects.all(), }
    format = json and "json" or "html"
    return render_to_response('ejeje/directory.%s' % format, ctx)

def about(request):
    return render_to_response('ejeje/about.html', {})

def news(request, newsid=None, tag=None, format=None):
    if format is None or format.lower() not in ('html', 'atom', 'json'):
        format = 'html'
    ctx = {'object':None, 'list':[]}
    if tag is not None:
        pass # TODO: Implement tags
        #ctx['list'] = Nyhet. 
    elif newsid is None:
        ctx['list'] = Nyhet.objects.exclude(aktiv=False)
    else:
        ctx['object'] = get_object_or_404(Nyhet, pk=newsid)
    return render_to_response('ejeje/news.%s' % format.lower(), ctx)

def details(request, table, pid, json=False):
    safe_tables = ('postjournal', 'postjournal_logg', 'postjournal_forslag', 'enkeltjournal', 'adressat', 'organisasjon', 'saksbehandler', 'journalpost', 'innsyn', )
    if not table in safe_tables:
        return HttpResponseBadRequest("""You shan't see that table""")
    import ejejeweb.ejeje.models as m
    klass = getattr(m, table.title())
    obj = get_object_or_404(klass, pk=pid)
    tpl = 'ejeje/layout.html'
    if 'frameless' in request.GET and request.GET['frameless'] == '1':
        tpl = 'ejeje/details.html'
    return render_to_response('ejeje/details-%s.html' % table.lower(), {'object':obj, 'template':tpl})

def login(request, json=None):
    username = request.POST['username']
    password = request.POST['password']
    user = django_auth(username=username, password=password)
    if user is not None:
        if user.is_active:
            django_login(request, user)
            if json:
                return HttpResponse("You make it")
            else:
                render_to_response('ejeje/logged_in.html', {'req':request})
        else:
            # Return a 'disabled account' error message
            if json:
                return HttpResponseNotAllowed("Account disowned and disabled!")
            else:
                render_to_response('ejeje/login_failed.html', {'req':request})
    else:
        # Return an 'invalid login' error message.
        if json:
            return HttpResponseNotAllowed("No username password matchy!")
        else:
            render_to_response('ejeje/login_failed.html', {'req':request})

